<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="filterElements"
        @submit="handleSearch"
        @reset="resetForm"
      >
        <Button
          style="display: inline-block;"
          @click="handleExport"
        >导出</Button>
      </FilterForm>
    </Container>
    <Container height="fill" :scroll-y="true" display="flexY">
      <OperationContainer style="margin-bottom: 10px">
        <!-- <Button style="margin-right: 12px" @click="actionUnfoldFunc(true)"
          >导出</Button
        > -->
      </OperationContainer>
      <el-table
        ref="tableref"
        v-loading="tableLoading"
        :data="tableData"
        border
        :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8',textAlign:'left' }"
        header-row-class-name="ck-table-header"
        row-class-name="ck-table-row"
        size="small"
        row-key="code"
        height="100%"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column align="center" type="index" label="" width="60" />
        <el-table-column label="科室代码" prop="deptCode" width="80" />
        <el-table-column prop="deptName" label="科室名称" />
        <el-table-column prop="personnel" label="人员经费" align="right">
          <template slot-scope="scope">
            <div class="text-btn" @click="btnPerDetails(scope.row)">
              <!-- {{ scope.row.personnel }} -->
              {{ scope.row.personnel | numberToCurrency }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="drug" label="药品费" align="right">
          <template slot-scope="scope">
            <div class="text-btn" @click="btnCostDetails(scope.row)">
              <!-- {{ scope.row.drug }} -->
              {{ scope.row.drug | numberToCurrency }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sanitaryMaterials" label="卫生材料费" align="right">
          <template slot-scope="scope">
            <div class="text-btn" @click="handleWscl(scope.row)">
              <!-- {{ scope.row.sanitaryMaterials }} -->
              {{ scope.row.sanitaryMaterials | numberToCurrency }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="fixed" label="固定资产折旧费" align="right">
          <template slot-scope="scope">
            <div class="text-btn" @click="btnAssetsDetails(scope.row)">
              <!-- {{ scope.row.fixed }} -->
              {{ scope.row.fixed | numberToCurrency }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="intangible" label="无形资产摊销" align="right">
          <template slot-scope="scope">
            <div class="text-btn" @click="handleWxzc(scope.row)">
              <!-- {{ scope.row.intangible }} -->
              {{ scope.row.intangible | numberToCurrency }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="risk" label="提取医疗风险基金" align="right">
          <template slot-scope="scope">
            <div class="text-btn">
              <!-- {{ scope.row.risk }} -->
              {{ scope.row.risk | numberToCurrency }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="other" label="其他费用" align="right">
          <template slot-scope="scope">
            <div class="text-btn" @click="btnExpensesDetails(scope.row)">
              <!-- {{ scope.row.other }} -->
              {{ scope.row.other | numberToCurrency }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sum" label="总计" align="right">
          <template slot-scope="scope">
            {{ scope.row.sum | numberToCurrency }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="导出"
              placement="top"
            >
              <i
                class="el-icon-download"
                style="
                  padding-top: 4px;
                  font-size: 20px;
                  color: #207efa;
                  cursor: pointer;
                "
                @click="handlePerDeptExport(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagenation-box">
        <!-- 分页 -->
        <!-- <Pagination
          :total="pageAttr.total"
          :page="pageAttr.currentPage"
          :page-size="pageAttr.pageSize"
          @pagation="pagationChange"
        /> -->
      </div>
      <!-- 科室代码 -->
      <DeptDetails
        v-if="deptVisible"
        :dept-visible="deptVisible"
        @handleCoseDept="handleCoseDept"
      />
      <!-- 人员经费 -->
      <PersonnelFundsDetails
        :funds-per-details-visible="fundsPerDetailsVisible"
        :table-ry-jf-col="tableRyJfCol"
        :table-ryjf-data="tableRyjfData"
        @fundsPerDetails="fundsPerDetails"
      />
      <!-- 药品费 -->
      <DrugCostDetails
        v-if="drugCostDetailsVisible"
        :drug-cost-details-visible="drugCostDetailsVisible"
        :table-drug-data="tableDrugData"
        @drugCostDetails="drugCostDetails"
      />
      <!-- 卫生材料费 -->
      <Wsclfee
        v-if="wsclVisible"
        :wscl-visible="wsclVisible"
        :table-wscl-data="tableWsclData"
        @handleCloseWS="handleCloseWS"
      />
      <!-- 无形资产摊销 -->
      <WxzcTanxiao
        v-if="wxzcVisible"
        :wxzc-visible="wxzcVisible"
        :table-wxzc-data="tableWxzcData"
        @handleCloseWxzc="handleCloseWxzc"
      />
      <!-- 固定资产 折旧 -->
      <FixedAssetsDetails
        v-if="fixedAssetsDetailsVisible"
        :fixed-assets-details-visible="fixedAssetsDetailsVisible"
        :table-gdzc-data="tableGdzcData"
        @fixedAssetsDetails="fixedAssetsDetails"
      />
      <!-- 其他费用 -->
      <OtherExpensesDetails
        v-if="otherExpensesDetailsVisible"
        :other-expenses-details-visible="otherExpensesDetailsVisible"
        :table-other-data="tableOtherData"
        @otherExpensesDetails="otherExpensesDetails"
      />
    </Container>
  </ContainerGroup>
</template>

<script>
import DeptDetails from '../perMonthDrawer/deptDetails.vue'
import PersonnelFundsDetails from '../perMonthDrawer/PersonnelFundsDetails.vue'
import DrugCostDetails from '../perMonthDrawer/DrugCostDetails.vue'
import FixedAssetsDetails from '../perMonthDrawer/FixedAssetsDetails.vue'
import OtherExpensesDetails from '../perMonthDrawer/OtherExpensesDetails.vue'
import Wsclfee from '../perMonthDrawer/wsclfee.vue'
import WxzcTanxiao from '../perMonthDrawer/wxzcTanxiao.vue'
import {
  getAllBaseCostByDate,
  listBaseCostGroupDept,
  listDrugCostByPDeptCode,
  getAcSetSource,
  listSalaryWithExtraByPDeptCode,
  listDepreciationByPDeptCode,
  numberToCurrencyNo,
  downloadDeptPerMonth,
  perDeptdownloadPerMonth
} from '@/utils/apis/report'

export default {
  name: 'PerMonth', // 医院各科室单月直接成本表
  components: {
    PersonnelFundsDetails,
    DrugCostDetails,
    FixedAssetsDetails,
    OtherExpensesDetails,
    DeptDetails,
    Wsclfee,
    WxzcTanxiao
  },
  provide() {
    return { tableRoot: this }
  },
  data() {
    return {
      filterElements: [
        {
          key: 'yearMonth',
          type: 'date-picker',
          label: '年/月',
          mode: 'monthrange',
          type: 'date-picker',
          format: 'yyyy-MM',
          value: [this.$util.currentDate(), this.$util.currentDate()],
          width: 340
        }
        // {
        //   key: "aihao",
        //   type: "Select",
        //   label: "院区",
        //   value: "",
        //   width: 210,
        //   options: [
        //     {
        //       label: "全部",
        //       value: "1",
        //     },
        //     {
        //       label: "浒关院区",
        //       value: "2",
        //     },
        //     {
        //       label: "三香院区",
        //       value: "3",
        //     },
        //   ],
        // },
      ],
      pageAttr: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      tableData: [],
      tableLoading: false,
      deptVisible: false, // 科室代码
      deptCode: '',
      fundsPerDetailsVisible: false, // 人员经费列表
      tableRyJfCol: [],
      tableRyjfData: [],
      drugCostDetailsVisible: false, // 药品费用详情
      wsclVisible: false, // 卫生材料费
      fixedAssetsDetailsVisible: false, // 固定资产折旧费详情
      tableGdzcData: [],
      otherExpensesDetailsVisible: false, // 其他费用详情
      wxzcVisible: false, // 无形资产摊销
      newParamList: {},
      tableDrugData: [],
      tableOtherData: [],
      tableWsclData: [],
      tableWxzcData: []
    }
  },
  created() {},
  mounted() {},
  updated() {
    if (this.$refs.tableref) {
      this.$refs.tableref.doLayout()
    }
  },
  methods: {
    handlePerDeptExport(row) {
      const fieldVal = this.$refs.filterForm.getParms()
      const date = fieldVal?.yearMonth
      const param = {
        yard: '1',
        starYear: this.$moment(date[0]).format('YYYY'),
        endYear: this.$moment(date[1]).format('YYYY'),
        starMonth: this.$moment(date[0]).format('MM'),
        endMonth: this.$moment(date[1]).format('MM')
      }
      perDeptdownloadPerMonth(param, row.deptCode).then(res => {
        const blob = new Blob([res.data], {
          type: res.data.type + 'charset=utf-8'
        })
        const downloadLink = document.createElement('a')
        const URL = window.URL || window.webkitURL || window.moxURL
        const downUrl = URL.createObjectURL(blob)
        downloadLink.href = downUrl
        downloadLink.download = '单科室单月成本表.xlsx'
        downloadLink.click()
        window.URL.revokeObjectURL(downUrl)
        // document.body.removeChild(downloadLink) // 删除 a 标签
      })
    },
    handleExport() { // 导出
      const fieldVal = this.$refs.filterForm.getParms()
      const date = fieldVal?.yearMonth
      const param = {
        yard: '1',
        starYear: this.$moment(date[0]).format('YYYY'),
        endYear: this.$moment(date[1]).format('YYYY'),
        starMonth: this.$moment(date[0]).format('MM'),
        endMonth: this.$moment(date[1]).format('MM')
      }
      downloadDeptPerMonth(param).then(res => {
        const blob = new Blob([res.data], {
          type: res.data.type + 'charset=utf-8'
        })
        const downloadLink = document.createElement('a')
        const URL = window.URL || window.webkitURL || window.moxURL
        const downUrl = URL.createObjectURL(blob)
        downloadLink.href = downUrl
        downloadLink.download = '各科室单月直接成本表.xlsx'
        downloadLink.click()
        window.URL.revokeObjectURL(downUrl)
        // document.body.removeChild(downloadLink) // 删除 a 标签
      })
    },
    // 指定列求和
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (index >= 3 && index <= 10) {
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)

              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = this.$numberToCurrencyNo(sums[index].toFixed(2))
          } else {
            sums[index] = 'N/A'
          }
        }
      })
      return sums
    },
    handleCloseWxzc(res) {
      this.wxzcVisible = res.wxzcVisible
    },
    handleWxzc(row) {
      // 无形资产摊销
      this.deptCode = row.deptCode
      this.costItemCode = row.costItemCode
      this.wxzcVisible = true
      this.getCommonWxZj(row, 'tableWxzcData', 'ZC058')
    },
    getCommonWxZj(row, tableData, unitCode) {
      const date = this.newParamList.yearMonth
      const param = {
        yard: '1',
        unitCode: unitCode,
        starYear: this.$moment(date[0]).format('YYYY'),
        endYear: this.$moment(date[1]).format('YYYY'),
        starMonth: this.$moment(date[0]).format('MM'),
        endMonth: this.$moment(date[1]).format('MM')
      }
      listDepreciationByPDeptCode(param, row.deptCode).then((res) => {
        if (res.data.code === 200) {
          this[tableData] = res.data.data
        }
      })
    },
    handleCloseWS(res) {
      this.wsclVisible = res.wsclVisible
    },
    handleWscl(row) {
      // 卫生材料费
      this.deptCode = row.deptCode
      this.wsclVisible = true
      this.getChildData('tableWsclData', '102', this.deptCode)
    },
    handleCoseDept(res) {
      this.deptVisible = res.deptVisible
    },
    handleDept(row) {
      // 科室代码
      this.deptCode = row.deptCode
      this.deptVisible = true
    },
    // 分页
    pagationChange(payload) {
      this.pageAttr.currentPage = payload.page
      this.pageAttr.pageSize = payload.pageSize
      this.getData(this.newParamList)
    },
    resetForm() {
      location.reload()
    },
    handleSearch(value) {
      this.newParamList = value
      this.pageAttr.currentPage = 1
      this.getData()
    },
    createNewData() {},
    getData() {
      // 列表
      const date = this.newParamList.yearMonth
      const param = {
        pageNum: this.pageAttr.currentPage,
        pageSize: this.pageAttr.pageSize,
        yard: '1',
        starYear: this.$moment(date[0]).format('YYYY'),
        endYear: this.$moment(date[1]).format('YYYY'),
        starMonth: this.$moment(date[0]).format('MM'),
        endMonth: this.$moment(date[1]).format('MM')
      }
      this.tableLoading = true
      listBaseCostGroupDept(param).then((res) => {
        if (res.data.code === 200) {
          this.tableData = res.data.data
        }
        this.tableLoading = false
      })
    },
    formatNumber(n) {
      n = n.toString()
      return n[1] ? n : `0${n}`
    },
    // 人员经费列表
    btnPerDetails(row) {
      this.fundsPerDetailsVisible = true
      this.deptCode = row.deptCode
      // this.getChildData("tableOtherData", "107", this.deptCode);
      this.getAcSetSourceList()
      this.getListSalaryWithAccByPDeptCode()
    },
    getAcSetSourceList() {
      const date = this.newParamList.yearMonth
      const param = {
        starYear: this.$moment(date[0]).format('YYYY'),
        endYear: this.$moment(date[1]).format('YYYY'),
        starMonth: this.$moment(date[0]).format('MM'),
        endMonth: this.$moment(date[1]).format('MM')
      }
      getAcSetSource(param).then((res) => {
        if (res.data.code === 200) {
          this.tableRyJfCol = res.data.data
        }
      })
    },
    getListSalaryWithAccByPDeptCode() {
      const date = this.newParamList.yearMonth
      const param = {
        yard: '1',
        starYear: this.$moment(date[0]).format('YYYY'),
        endYear: this.$moment(date[1]).format('YYYY'),
        starMonth: this.$moment(date[0]).format('MM'),
        endMonth: this.$moment(date[1]).format('MM')
      }
      listSalaryWithExtraByPDeptCode(param, this.deptCode).then((res) => {
        if (res.data.code === 200) {
          this.tableRyjfData = res.data.data
        }
      })
    },
    fundsPerDetails(params) {
      this.fundsPerDetailsVisible = params.fundsPerDetailsVisible
    },
    // 药品费用详情
    btnCostDetails(row) {
      this.deptCode = row.deptCode
      this.drugCostDetailsVisible = true
      this.getChildData('tableDrugData', '103', this.deptCode)
    },
    drugCostDetails(params) {
      this.drugCostDetailsVisible = params.drugCostDetailsVisible
    },
    // 固定资产折旧费详情
    btnAssetsDetails(row) {
      this.fixedAssetsDetailsVisible = true
      this.getCommonWxZj(row, 'tableGdzcData', 'ZC057')
    },

    fixedAssetsDetails(params) {
      this.fixedAssetsDetailsVisible = params.fixedAssetsDetailsVisible
    },
    // 其他费用详情
    btnExpensesDetails(row) {
      this.otherExpensesDetailsVisible = true
      this.deptCode = row.deptCode
      this.getChildData('tableOtherData', '107', this.deptCode)
    },
    otherExpensesDetails(params) {
      this.otherExpensesDetailsVisible = params.otherExpensesDetailsVisible
    },
    getChildData(tableList, unitCode, deptCode) {
      const date = this.newParamList.yearMonth
      const param = {
        yard: '1',
        unitCode: unitCode,
        starYear: this.$moment(date[0]).format('YYYY'),
        endYear: this.$moment(date[1]).format('YYYY'),
        starMonth: this.$moment(date[0]).format('MM'),
        endMonth: this.$moment(date[1]).format('MM')
      }
      listDrugCostByPDeptCode(param, deptCode).then((res) => {
        if (res.data.code === 200) {
          this[tableList] = res.data.data
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-table--mini,
.el-table--small,
.el-table__expand-icon {
  font-size: 14px !important;
}

.ck-table-header {
  th {
    background: #fafafa !important;
    height: 48px;
    color: #555555 !important;
  }
}
.pagenation-box {
  display: flex;
  padding-top: 2px;
  justify-content: flex-end;
}
.text-btn {
  color: #2165f9;
  border-bottom: 1px solid #2165f9;
  display: inline-block !important;
  cursor: pointer;
}
</style>
